<template>
  <div class="lakala-page-wrapper">
    <!-- 主内容区域 -->
    <div id="app" class="main-container">
      <!-- 左侧表单区域 -->
      <div class="form-container">
        <!-- 页面标题 -->
        <div class="form-header">
          <h2 class="form-title">拉卡拉电子合同申请</h2>
          <div class="form-subtitle">测试环境 - EC008 特约商户支付服务合作协议</div>
        </div>

        <form @submit.prevent="submitContract" class="contract-form">
          <!-- 基础信息 -->
          <fieldset>
            <legend>基础信息</legend>

            <div class="form-group">
              <label class="form-label">订单号：</label>
              <div class="form-control-group">
                <input v-model="formData.order_no" type="text" class="form-input" readonly />
                <button type="button" @click="generateOrderNo" class="btn btn-secondary">生成订单号</button>
              </div>
            </div>

            <div class="form-group">
              <label class="form-label">机构号：</label>
              <input v-model="formData.org_id" type="number" class="form-input" required />
            </div>

            <div class="form-group">
              <label class="form-label">合同类型：</label>
              <select v-model="formData.ec_type_code" class="form-select" required>
                <option value="EC008">EC008 - 特约商户支付服务合作协议V4.1（商户入网）</option>
                <option value="EC007">EC007 - 特约商户支付服务合作协议V4.1+分账</option>
                <option value="EC009">EC009 - 清分结算授权委托书</option>
              </select>
            </div>
          </fieldset>

          <!-- 商户信息 -->
          <fieldset>
            <legend>商户信息</legend>

            <div class="form-group">
              <label class="form-label">商户类型：</label>
              <select v-model="merchantType" @change="onMerchantTypeChange" class="form-select">
                <option value="individual">小微个人商户（无营业执照）</option>
                <option value="business">个体工商户/企业商户（有营业执照）</option>
              </select>
            </div>

            <div v-if="merchantType === 'business'" class="form-group">
              <label class="form-label">营业执照号：</label>
              <input v-model="formData.business_license_no" type="text" class="form-input" :required="merchantType === 'business'" />
            </div>

            <div v-if="merchantType === 'business'" class="form-group">
              <label class="form-label">营业执照名称：</label>
              <input v-model="formData.business_license_name" type="text" class="form-input" :required="merchantType === 'business'" />
            </div>
          </fieldset>

          <!-- 法人/经营者信息 -->
          <fieldset>
            <legend>法人/经营者信息</legend>

            <div class="form-group">
              <label class="form-label">证件类型：</label>
              <select v-model="formData.cert_type" class="form-select" required>
                <option value="RESIDENT_ID">身份证</option>
                <option value="PASSPORT">护照</option>
                <option value="HK_MACAO_PASS">港澳居民往来内地通行证</option>
                <option value="TAIWAN_PASS">台湾居民来往大陆通行证</option>
              </select>
            </div>

            <div class="form-group">
              <label class="form-label">姓名：</label>
              <input v-model="formData.cert_name" type="text" class="form-input" required />
            </div>

            <div class="form-group">
              <label class="form-label">证件号码：</label>
              <input v-model="formData.cert_no" type="text" class="form-input" required />
            </div>

            <div class="form-group">
              <label class="form-label">签约手机号：</label>
              <input v-model="formData.mobile" type="tel" pattern="[0-9]{11}" class="form-input" required />
              <small class="form-hint">合同签署人手机号，请慎重填写，不可修改</small>
            </div>
          </fieldset>

          <!-- 结算账户信息 -->
          <fieldset>
            <legend>结算账户信息</legend>

            <div class="form-group">
              <label class="form-label">开户行号：</label>
              <input v-model="formData.openning_bank_code" type="text" class="form-input" required />
            </div>

            <div class="form-group">
              <label class="form-label">开户行名称：</label>
              <input v-model="formData.openning_bank_name" type="text" class="form-input" required />
            </div>

            <div class="form-group">
              <label class="form-label">账户性质：</label>
              <select v-model="formData.acct_type_code" class="form-select" required>
                <option value="57">对公</option>
                <option value="58">对私</option>
              </select>
            </div>

            <div class="form-group">
              <label class="form-label">结算账号：</label>
              <input v-model="formData.acct_no" type="text" class="form-input" required />
            </div>

            <div class="form-group">
              <label class="form-label">账户名称：</label>
              <input v-model="formData.acct_name" type="text" class="form-input" required />
            </div>
          </fieldset>

          <!-- EC008核心参数 -->
          <fieldset>
            <legend>合同核心参数（EC008）</legend>

            <div class="form-group">
              <label class="form-label">A1-商户名称：</label>
              <input v-model="ecParams.A1" type="text" class="form-input" required />
            </div>

            <div class="form-group">
              <label class="form-label">A29-支付宝费率(%)：</label>
              <input v-model="ecParams.A29" type="number" step="0.01" min="0" max="100" class="form-input" />
            </div>

            <div class="form-group">
              <label class="form-label">A30-微信费率(%)：</label>
              <input v-model="ecParams.A30" type="number" step="0.01" min="0" max="100" class="form-input" />
            </div>

            <div class="form-group">
              <label class="form-label">A31-京东费率(%)：</label>
              <input v-model="ecParams.A31" type="number" step="0.01" min="0" max="100" class="form-input" />
            </div>

            <div class="form-group">
              <label class="form-label">A96-默认结算模式：</label>
              <select v-model="ecParams.A96" class="form-select" required>
                <option value="T0">T0结算</option>
                <option value="T1">T1结算</option>
              </select>
            </div>

            <div class="form-group">
              <label class="form-label">B1-登记表年份：</label>
              <input v-model="ecParams.B1" type="number" class="form-input" required />
            </div>

            <div class="form-group">
              <label class="form-label">B2-登记表月份：</label>
              <input v-model="ecParams.B2" type="number" min="1" max="12" class="form-input" required />
            </div>

            <div class="form-group">
              <label class="form-label">B9-主营业务：</label>
              <input v-model="ecParams.B9" type="text" placeholder="如：餐饮服务" class="form-input" required />
            </div>

            <div class="form-group">
              <label class="form-label">B10-对外经营名称：</label>
              <input v-model="ecParams.B10" type="text" class="form-input" required />
            </div>

            <div class="form-group">
              <label class="form-label">D1-授权书签章日期：</label>
              <input v-model="ecParams.D1" type="date" class="form-input" required />
            </div>

            <div class="form-group">
              <label class="form-label">D12-电子签约授权日期：</label>
              <input v-model="ecParams.D12" type="date" class="form-input" required />
            </div>
          </fieldset>

          <!-- 经办人信息（可选） -->
          <fieldset>
            <legend>经办人信息（可选）</legend>

            <div class="form-group">
              <label class="checkbox-label">
                <input v-model="formData.agent_tag" type="checkbox" :true-value="1" :false-value="0" />
                启用经办人签约
              </label>
            </div>

            <div v-if="formData.agent_tag === 1" class="form-group">
              <label class="form-label">经办人姓名：</label>
              <input v-model="formData.agent_name" type="text" class="form-input" :required="formData.agent_tag === 1" />
            </div>

            <div v-if="formData.agent_tag === 1" class="form-group">
              <label class="form-label">经办人证件类型：</label>
              <select v-model="formData.agent_cert_type" class="form-select" :required="formData.agent_tag === 1">
                <option value="RESIDENT_ID">身份证</option>
                <option value="PASSPORT">护照</option>
                <option value="HK_MACAO_PASS">港澳居民往来内地通行证</option>
                <option value="TAIWAN_PASS">台湾居民来往大陆通行证</option>
              </select>
            </div>

            <div v-if="formData.agent_tag === 1" class="form-group">
              <label class="form-label">经办人证件号：</label>
              <input v-model="formData.agent_cert_no" type="text" class="form-input" :required="formData.agent_tag === 1" />
            </div>
          </fieldset>

          <!-- 其他信息 -->
          <fieldset>
            <legend>其他信息</legend>

            <div class="form-group">
              <label class="form-label">备注：</label>
              <textarea v-model="formData.remark" rows="3" class="form-textarea"></textarea>
            </div>

            <div class="form-group">
              <label class="form-label">回调通知URL：</label>
              <input v-model="formData.ret_url" type="url" placeholder="http://example.com/callback" class="form-input" />
            </div>
          </fieldset>

          <!-- 提交按钮 -->
          <div class="form-actions">
            <button type="submit" class="btn btn-primary" :disabled="loading">
              {{ loading ? '提交中...' : '提交申请' }}
            </button>
            <button type="button" @click="resetForm" class="btn btn-default">重置表单</button>
            <!-- 一键填充测试数据按钮 -->
            <button type="button" @click="autoFillTestData" class="btn btn-secondary">一键填充测试数据</button>
            <!-- 一键填充并提交 -->
            <button type="button" @click="autoFillAndSubmit" class="btn btn-secondary" :disabled="loading">一键填充并提交</button>
          </div>
        </form>
      </div>

      <!-- 右侧响应展示区域 -->
      <div class="response-container">
        <h3 class="response-title">响应结果</h3>

        <!-- 初始状态 -->
        <div v-if="!response && !loading && !error" class="response-empty">
          <p>请填写表单并提交申请</p>
          <ul class="response-tips">
            <li>填写完整的商户信息</li>
            <li>确认所有必填项</li>
            <li>点击"提交申请"按钮</li>
          </ul>
        </div>

        <!-- 加载中 -->
        <div v-if="loading" class="response-loading">
          <p>正在提交申请...</p>
          <p>请稍候...</p>
        </div>

        <!-- 成功响应 -->
        <div v-if="response && response.code === '000000'" class="response-success">
          <h4 class="success-title">申请成功</h4>

          <div class="response-item">
            <strong>订单号：</strong>
            <span>{{ response.resp_data?.order_no }}</span>
          </div>

          <div class="response-item">
            <strong>受理编号：</strong>
            <span>{{ response.resp_data?.ec_apply_id }}</span>
          </div>

          <div class="response-item">
            <strong>签约链接：</strong>
            <div v-if="response.resp_data?.result_url" class="result-url">
              <a :href="response.resp_data.result_url" target="_blank" class="sign-link">
                点击前往签约
              </a>
              <br/>
              <textarea :value="response.resp_data.result_url" readonly rows="3" class="url-textarea"></textarea>

              <!-- 生成二维码 -->
              <div v-if="qrCodeUrl">
                <p>扫码签约：</p>
                <img :src="qrCodeUrl" alt="签约二维码" style="width: 200px; height: 200px;" />
              </div>
            </div>
          </div>

          <!-- 操作按钮 -->
          <div class="response-actions">
            <button @click="queryContractStatus" class="btn btn-secondary" :disabled="queryLoading">
              {{ queryLoading ? '查询中...' : '查询签约状态' }}
            </button>
            <button v-if="contractStatus?.ecNo" @click="downloadContract" class="btn btn-primary" :disabled="downloadLoading">
              {{ downloadLoading ? '下载中...' : '下载合同' }}
            </button>
          </div>

          <!-- 合同状态显示 -->
          <div v-if="contractStatus" class="contract-status">
            <h5>合同状态</h5>
            <div class="status-item">
              <strong>状态：</strong>
              <span :class="getStatusClass(contractStatus.status)">{{ getStatusText(contractStatus.status) }}</span>
            </div>
            <div v-if="contractStatus.ecNo" class="status-item">
              <strong>合同编号：</strong>
              <span>{{ contractStatus.ecNo }}</span>
            </div>
            <div v-if="contractStatus.signTime" class="status-item">
              <strong>签约时间：</strong>
              <span>{{ formatDate(contractStatus.signTime) }}</span>
            </div>
          </div>
        </div>

        <!-- 错误响应 -->
        <div v-if="error || (response && response.code !== '000000')" class="response-error">
          <h4 class="error-title">申请失败</h4>

          <div v-if="response" class="response-item">
            <strong>错误码：</strong>
            <span>{{ response.code }}</span>
          </div>

          <div class="response-item">
            <strong>错误信息：</strong>
            <span>{{ error || response?.message || response?.msg }}</span>
          </div>

          <div v-if="response?.code === '087900'" class="warning-tip">
            <p>提示：三四要素认证失败，可申请转人工复核</p>
          </div>
        </div>

        <!-- 原始响应数据 -->
        <div v-if="response" class="raw-data">
          <h4 class="section-title">原始响应数据</h4>
          <pre class="code-block">{{ JSON.stringify(response, null, 2) }}</pre>
        </div>

        <!-- 请求参数预览 -->
        <div class="raw-data">
          <h4 class="section-title">请求参数预览</h4>
          <pre class="code-block">{{ JSON.stringify(getRequestData(), null, 2) }}</pre>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, onUnmounted } from 'vue'

// API地址配置
// 调用后端接口
const API_BASE = '/api/lakala/contract'
const API_APPLY = `${API_BASE}/apply`
const API_QUERY = `${API_BASE}/query`
const API_DOWNLOAD = `${API_BASE}/download`
const API_GENERATE_ORDER_NO = `${API_BASE}/generate-order-no`

// 表单数据
const formData = reactive({
  order_no: '',
  org_id: 1,
  ec_type_code: 'EC008',
  cert_type: 'RESIDENT_ID',
  cert_name: '',
  cert_no: '',
  mobile: '',
  business_license_no: '',
  business_license_name: '',
  openning_bank_code: '',
  openning_bank_name: '',
  acct_type_code: '58',
  acct_no: '',
  acct_name: '',
  ec_content_parameters: '',
  agent_tag: 0,
  agent_name: '',
  agent_cert_type: 'RESIDENT_ID',
  agent_cert_no: '',
  agent_file_name: '',
  agent_file_path: '',
  remark: '',
  ret_url: ''
})

// EC008参数
const ecParams = reactive({
  A1: '', // 商户名称
  A29: '', // 支付宝费率
  A30: '', // 微信费率
  A31: '', // 京东费率
  A32: '', // 拉卡拉钱包费率
  A33: '', // 数字人民币费率
  A96: 'T1', // 默认结算模式
  A104: '', // 甲方签约年
  A105: '', // 甲方签约月
  A106: '', // 甲方签约日
  A107: '', // 乙方签约年
  A108: '', // 乙方签约月
  A109: '', // 乙方签约日
  B1: new Date().getFullYear(), // 登记表年
  B2: new Date().getMonth() + 1, // 登记表月
  B8: '', // 工商注册名称
  B9: '', // 主营业务
  B10: '', // 对外经营名称
  B11: '', // 办公地址
  B13: '', // 营业地址
  B14: '', // 营业执照号
  B16: '', // 结算账户名称
  B19: '', // 开户行
  B20: '', // 结算账号
  B24: '', // 法人姓名
  B25: '', // 法人证件号
  B26: '', // 法人手机
  B27: '', // 联系人姓名
  B28: '', // 联系人邮箱
  B29: '', // 联系人证件号
  B30: '', // 联系人手机
  D1: '', // 授权书银行签章日期
  D2: '', // 授权书银行法人姓名
  D4: '', // 数据处理方授权书商户名称
  D5: '', // 数据处理方授权书法人姓名
  D7: '', // 数据处理方授权书签章日期
  D12: '' // 电子签约授权委托书签章日期
})

// 商户类型
const merchantType = ref('individual')

// 状态
const loading = ref(false)
const response = ref<any>(null)
const error = ref('')
const qrCodeUrl = ref('')
const queryLoading = ref(false)
const downloadLoading = ref(false)
const contractStatus = ref<any>(null)

// 当前年月
const currentYear = new Date().getFullYear()
const currentMonth = new Date().getMonth() + 1

// 生成订单号
const generateOrderNo = () => {
  const timestamp = new Date().getTime()
  const random = Math.random().toString(36).substring(2, 10)
  formData.order_no = `EC${timestamp}${random}`.substring(0, 32)
}

// 商户类型变化
const onMerchantTypeChange = () => {
  if (merchantType.value === 'individual') {
    formData.business_license_no = ''
    formData.business_license_name = ''
  }
}

// 获取请求数据 (返回snake_case格式，与后端@JsonProperty注解匹配)
const getRequestData = (): Record<string, any> => {
  // 自动填充一些EC参数
  const now = new Date()
  if (!ecParams.A104) ecParams.A104 = String(now.getFullYear())
  if (!ecParams.A105) ecParams.A105 = String(now.getMonth() + 1)
  if (!ecParams.A106) ecParams.A106 = String(now.getDate())
  if (!ecParams.A107) ecParams.A107 = String(now.getFullYear())
  if (!ecParams.A108) ecParams.A108 = String(now.getMonth() + 1)
  if (!ecParams.A109) ecParams.A109 = String(now.getDate())

  // 自动填充B系列参数
  if (!ecParams.B8) ecParams.B8 = formData.business_license_name || formData.cert_name
  if (!ecParams.B14) ecParams.B14 = formData.business_license_no
  if (!ecParams.B16) ecParams.B16 = formData.acct_name
  if (!ecParams.B19) ecParams.B19 = formData.openning_bank_name
  if (!ecParams.B20) ecParams.B20 = formData.acct_no
  if (!ecParams.B24) ecParams.B24 = formData.cert_name
  if (!ecParams.B25) ecParams.B25 = formData.cert_no
  if (!ecParams.B26) ecParams.B26 = formData.mobile
  if (!ecParams.B27) ecParams.B27 = formData.cert_name
  if (!ecParams.B29) ecParams.B29 = formData.cert_no
  if (!ecParams.B30) ecParams.B30 = formData.mobile

  // 自动填充D系列参数
  if (!ecParams.D2) ecParams.D2 = formData.cert_name
  if (!ecParams.D4) ecParams.D4 = ecParams.A1
  if (!ecParams.D5) ecParams.D5 = formData.cert_name
  if (!ecParams.D7) ecParams.D7 = ecParams.D1

  // 构建请求数据 - 使用snake_case命名（与后端@JsonProperty注解匹配）
  const reqData: any = {
    order_no: formData.order_no,
    org_id: formData.org_id,
    ec_type_code: formData.ec_type_code,
    cert_type: formData.cert_type,
    cert_name: formData.cert_name,
    cert_no: formData.cert_no,
    mobile: formData.mobile,
    openning_bank_code: formData.openning_bank_code,
    openning_bank_name: formData.openning_bank_name,
    acct_type_code: formData.acct_type_code,
    acct_no: formData.acct_no,
    acct_name: formData.acct_name,
    ec_content_parameters: JSON.stringify(ecParams),
    version: '1.0'
  }

  // 添加营业执照信息（如果有）
  if (merchantType.value === 'business') {
    reqData.business_license_no = formData.business_license_no
    reqData.business_license_name = formData.business_license_name
  }

  // 添加经办人信息
  reqData.agent_tag = formData.agent_tag || 0
  if (formData.agent_tag === 1) {
    reqData.agent_name = formData.agent_name
    reqData.agent_cert_type = formData.agent_cert_type
    reqData.agent_cert_no = formData.agent_cert_no
    reqData.agent_file_name = formData.agent_file_name || 'auth.pdf'
    reqData.agent_file_path = formData.agent_file_path || '/path/to/auth.pdf'
  }

  // 添加可选参数
  if (formData.remark) reqData.remark = formData.remark
  if (formData.ret_url) reqData.ret_url = formData.ret_url

  // 直接返回请求数据，不包装
  return reqData
}

// 提交表单
const submitContract = async () => {
  loading.value = true
  response.value = null
  error.value = ''
  qrCodeUrl.value = ''

  try {
    // 使用 getRequestData() 获取请求数据，确保预览与实际提交一致
    const requestData = getRequestData()

    // 移除值为 null 或 undefined 的字段
    Object.keys(requestData).forEach(key => {
      if (requestData[key] === null || requestData[key] === undefined || requestData[key] === '') {
        delete requestData[key]
      }
    })

    console.log('准备提交的数据：', requestData)

    // 调用后端接口
    const res = await fetch(API_APPLY, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        // 如果需要token认证
        'Authorization': localStorage.getItem('token') || ''
      },
      body: JSON.stringify(requestData)
    })

    const result = await res.json()
    console.log('后端响应：', result)

    if (result.code === 200 || result.code === '0') {
      // 后端返回成功
      const data = result.data
      response.value = {
        code: data.code || '000000',
        msg: data.message || result.message || '申请成功',
        resp_data: {
          order_no: data.respData?.orderNo || data.orderNo,
          ec_apply_id: data.respData?.ecApplyId || data.ecApplyId,
          result_url: data.respData?.resultUrl || data.resultUrl
        }
      }

      if (response.value.resp_data?.result_url) {
        console.log('签约链接：', response.value.resp_data.result_url)
        // 生成二维码
        generateQRCode(response.value.resp_data.result_url)
      }
    } else {
      // 后端返回失败
      error.value = result.message || '申请失败'
      response.value = {
        code: result.code,
        msg: result.message,
        resp_data: result.data
      }
    }
  } catch (err: any) {
    error.value = err.message || '提交失败'
    console.error('提交失败：', err)
  } finally {
    loading.value = false
  }
}

// 生成二维码（简单实现）
const generateQRCode = (url: string) => {
  // 使用第三方二维码API服务
  qrCodeUrl.value = `https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=${encodeURIComponent(url)}`
}

// 重置表单
const resetForm = () => {
  const fd: any = formData
  Object.keys(fd).forEach(key => {
    if (key === 'org_id') fd[key] = 1
    else if (key === 'ec_type_code') fd[key] = 'EC008'
    else if (key === 'cert_type') fd[key] = 'RESIDENT_ID'
    else if (key === 'acct_type_code') fd[key] = '58'
    else if (key === 'agent_tag') fd[key] = 0
    else if (key === 'agent_cert_type') fd[key] = 'RESIDENT_ID'
    else fd[key] = ''
  })

  const ep: any = ecParams
  Object.keys(ep).forEach(key => {
    if (key === 'A96') ep[key] = 'T1'
    else if (key === 'B1') ep[key] = currentYear
    else if (key === 'B2') ep[key] = currentMonth
    else ep[key] = ''
  })

  merchantType.value = 'individual'
  response.value = null
  error.value = ''
  qrCodeUrl.value = ''
}

// 查询合同状态
const queryContractStatus = async () => {
  if (!response.value?.resp_data?.order_no) {
    error.value = '无订单号，无法查询'
    return
  }

  queryLoading.value = true
  try {
    const orderNo = response.value.resp_data.order_no
    const res = await fetch(`${API_QUERY}/${orderNo}`, {
      method: 'GET',
      headers: {
        'Authorization': localStorage.getItem('token') || ''
      }
    })

    const result = await res.json()
    console.log('查询结果：', result)

    if (result.code === 200 || result.code === '0') {
      const data = result.data
      contractStatus.value = {
        status: data.status || 'UNKNOWN',
        ecNo: data.ecNo || data.ecApplyId,
        signTime: data.signTime,
        orderNo: data.orderNo,
        certName: data.certName,
        mobile: data.mobile
      }

      // 如果已签约且有合同号，显示成功提示
      if (contractStatus.value.ecNo && contractStatus.value.status === 'COMPLETED') {
        console.log('合同已签约，合同号：', contractStatus.value.ecNo)
      }
    } else {
      error.value = result.message || '查询失败'
    }
  } catch (err: any) {
    error.value = err.message || '查询失败'
    console.error('查询失败：', err)
  } finally {
    queryLoading.value = false
  }
}

// 下载合同
const downloadContract = async () => {
  if (!contractStatus.value?.ecNo) {
    error.value = '无合同编号，无法下载'
    return
  }

  downloadLoading.value = true
  try {
    const ecNo = contractStatus.value.ecNo
    const res = await fetch(`${API_DOWNLOAD}/${ecNo}`, {
      method: 'GET',
      headers: {
        'Authorization': localStorage.getItem('token') || ''
      }
    })

    if (res.ok) {
      // 获取文件内容
      const blob = await res.blob()
      const contentType = res.headers.get('content-type')

      // 判断是否为PDF
      if (contentType && contentType.includes('pdf')) {
        // 创建下载链接
        const url = window.URL.createObjectURL(blob)
        const a = document.createElement('a')
        a.href = url
        a.download = `contract_${ecNo}.pdf`
        document.body.appendChild(a)
        a.click()
        document.body.removeChild(a)
        window.URL.revokeObjectURL(url)

        console.log('合同下载成功')
      } else {
        // 如果不是PDF，可能是错误信息
        const text = await blob.text()
        try {
          const errorData = JSON.parse(text)
          error.value = errorData.message || '下载失败'
        } catch {
          error.value = '下载失败：返回格式错误'
        }
      }
    } else {
      const result = await res.json()
      error.value = result.message || '下载失败'
    }
  } catch (err: any) {
    error.value = err.message || '下载失败'
    console.error('下载失败：', err)
  } finally {
    downloadLoading.value = false
  }
}

// 获取状态文本
const getStatusText = (status: string) => {
  const statusMap: Record<string, string> = {
    'PENDING': '待提交',
    'SUBMITTED': '已提交',
    'SIGNING': '签约中',
    'COMPLETED': '已完成',
    'FAILED': '失败',
    'REJECTED': '已拒绝',
    'UNKNOWN': '未知'
  }
  return statusMap[status] || status
}

// 获取状态样式类
const getStatusClass = (status: string) => {
  const classMap: Record<string, string> = {
    'PENDING': 'status-pending',
    'SUBMITTED': 'status-submitted',
    'SIGNING': 'status-signing',
    'COMPLETED': 'status-completed',
    'FAILED': 'status-failed',
    'REJECTED': 'status-rejected',
    'UNKNOWN': 'status-unknown'
  }
  return classMap[status] || 'status-unknown'
}

// 格式化日期
const formatDate = (dateStr: string) => {
  if (!dateStr) return '-'
  const date = new Date(dateStr)
  return date.toLocaleString('zh-CN')
}

// 自动填充测试数据函数
const autoFillTestData = () => {
  // 设置商户类型为企业
  merchantType.value = 'business'

  // 填充基础信息
  formData.org_id = 1
  formData.ec_type_code = 'EC008'

  // 填充商户信息
  formData.business_license_no = '91110108MA01FPRF44'
  formData.business_license_name = '北京测试商贸有限公司'

  // 填充法人信息
  formData.cert_type = 'RESIDENT_ID'
  formData.cert_name = '张三'
  formData.cert_no = '110101199001011234'
  formData.mobile = '13800138000'

  // 填充结算账户
  formData.openning_bank_code = '403100000004'
  formData.openning_bank_name = '中国工商银行北京分行'
  formData.acct_type_code = '58'  // 对私
  formData.acct_no = '6222021001234567890'
  formData.acct_name = '张三'

  // 填充其他信息
  formData.remark = '测试申请'
  formData.ret_url = 'http://localhost:3000/callback'

  // 填充EC008核心参数
  ecParams.A1 = '北京测试商贸有限公司'
  ecParams.A29 = '0.38'  // 支付宝费率
  ecParams.A30 = '0.38'  // 微信费率
  ecParams.A31 = '0.38'  // 京东费率
  ecParams.A96 = 'T1'    // 结算模式
  ecParams.B1 = new Date().getFullYear()
  ecParams.B2 = new Date().getMonth() + 1
  ecParams.B9 = '餐饮服务'
  ecParams.B10 = '测试餐厅'
  ecParams.D1 = new Date().toISOString().split('T')[0]
  ecParams.D12 = new Date().toISOString().split('T')[0]

  // 生成新的订单号
  generateOrderNo()

  console.log('%c✓ 测试数据填充完成！', 'color: green; font-weight: bold')
  console.log('商户名称:', ecParams.A1)
  console.log('手机号:', formData.mobile)
  console.log('结算模式:', ecParams.A96)
  console.log('订单号:', formData.order_no)

  return {
    message: '数据已填充，请检查表单并点击"提交申请"',
    formData: formData,
    ecParams: ecParams
  }
}

// 新增：一键填充并提交方法，供模板调用
const autoFillAndSubmit = async () => {
  try {
    autoFillTestData()
    await submitContract()
  } catch (e) {
    console.error('一键填充并提交失败:', e)
  }
}

// 测试获取拉卡拉公钥的函数
const testGetPublicKey = async (appId = 'OP00002813') => {
  console.log('%c========== 开始测试获取拉卡拉公钥 ==========', 'color: blue; font-weight: bold')
  console.log('AppId:', appId)

  // 方案1：通过后端代理（推荐）
  console.log('\n%c方案1：通过后端代理请求', 'color: green; font-weight: bold')
  try {
    const proxyUrl = `/api/lakala/public-key/${appId}`
    console.log('代理URL:', proxyUrl)

    const res = await fetch(proxyUrl, {
      method: 'GET',
      headers: {
        'Accept': 'application/json',
        'Authorization': localStorage.getItem('token') || ''
      }
    })

    const data = await res.json()
    console.log('后端代理响应:', data)

    if (data.code === 200 || data.code === '0') {
      console.log('%c成功获取公钥！', 'color: green; font-weight: bold')
      console.log('公钥数据:', data.data)
    } else {
      console.log('%c获取失败', 'color: red')
      console.log('错误信息:', data.message)
    }
  } catch (error: any) {
    console.error('后端代理请求失败:', error)
  }

  // 方案2：直接请求（会被CORS阻止，但可以看到请求详情）
  console.log('\n%c方案2：直接请求（演示CORS问题）', 'color: orange; font-weight: bold')

  const urls = [
    { name: '测试环境', url: `https://test.wsmsd.cn/sit/gw/pubcerts?appId=${appId}` },
    { name: '生产环境', url: `https://s2.lakala.com/gw/pubcerts?appId=${appId}` },
    { name: '测试环境(路径格式)', url: `https://test.wsmsd.cn/sit/gw/pubcerts/${appId}` }
  ]

  const results = []

  for (const { name, url } of urls) {
    console.log(`\n%c测试 ${name}:`, 'color: green')
    console.log('URL:', url)

    try {
      // 尝试不同的请求方式
      const responses = []

      // 方式1: 简单GET请求
      try {
        const res1 = await fetch(url, {
          method: 'GET',
          headers: {
            'Accept': 'application/json'
          }
        })
        const data1 = await res1.json()
        responses.push({ method: '简单GET', status: res1.status, data: data1 })
        console.log('简单GET响应:', data1)
      } catch (e) {
        console.error('简单GET失败:', e)
      }

      // 方式2: 带User-Agent的请求
      try {
        const res2 = await fetch(url, {
          method: 'GET',
          headers: {
            'Accept': 'application/json',
            'User-Agent': 'LakalaOpenAPI/3.0'
          }
        })
        const data2 = await res2.json()
        responses.push({ method: '带User-Agent', status: res2.status, data: data2 })
        console.log('带User-Agent响应:', data2)
      } catch (e: any) {
        console.error('带User-Agent失败:', e)
      }

      // 方式3: 带Content-Type的请求
      try {
        const res3 = await fetch(url, {
          method: 'GET',
          headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json'
          }
        })
        const data3 = await res3.json()
        responses.push({ method: '带Content-Type', status: res3.status, data: data3 })
        console.log('带Content-Type响应:', data3)
      } catch (e: any) {
        console.error('带Content-Type失败:', e)
      }

      results.push({ name, url, responses })

    } catch (error: any) {
      console.error(`${name} 请求失败:`, error)
      results.push({ name, url, error: error.message })
    }
  }

  console.log('\n%c========== 测试完成 ==========', 'color: blue; font-weight: bold')
  console.log('所有结果:', results)

  // 分析结果
  console.log('\n%c========== 结果分析 ==========', 'color: purple; font-weight: bold')
  for (const result of results) {
    if (result.responses) {
      for (const res of result.responses) {
        if (res.data.code === 'GW0004') {
          console.log(`%c${result.name} - ${res.method}: 访问授权不通过`, 'color: red')
        } else if (res.data.code === '000000' || res.status === 200) {
          console.log(`%c${result.name} - ${res.method}: 成功！`, 'color: green; font-weight: bold')
          console.log('公钥数据:', res.data)
        } else {
          console.log(`${result.name} - ${res.method}: 其他响应`, res.data)
        }
      }
    }
  }

  return results
}

// 将函数暴露到window对象，方便控制台调用
declare global {
  interface Window {
    autoFillTestData: typeof autoFillTestData
    testGetPublicKey: typeof testGetPublicKey
  }
}

if (typeof window !== 'undefined') {
  window.autoFillTestData = autoFillTestData
  window.testGetPublicKey = testGetPublicKey
  console.log('%c拉卡拉电子合同申请页面已加载', 'color: blue; font-weight: bold')
  console.log('%c在控制台输入 autoFillTestData() 可自动填充测试数据', 'color: green')
  console.log('%c在控制台输入 testGetPublicKey() 测试获取拉卡拉公钥', 'color: orange')
  console.log('%c也可以指定appId: testGetPublicKey("OP00002813")', 'color: orange')
}

// 初始化
onMounted(() => {
  generateOrderNo()

  // 隐藏footer
  const footer = document.querySelector('.footer') as HTMLElement | null
  if (footer) {
    footer.style.display = 'none'
  }

  // 再次确保函数可用
  window.autoFillTestData = autoFillTestData
  window.testGetPublicKey = testGetPublicKey
})

// 组件卸载时恢复footer显示
onUnmounted(() => {
  const footer = document.querySelector('.footer') as HTMLElement | null
  if (footer) {
    footer.style.display = ''
  }
})
</script>

<!-- 使用style src方式导入所有CSS文件 -->
<style src="./assets/css/078019c1d0ad.css" scoped/>
<style src="./assets/css/21034fdb19a5.css" scoped/>
<style src="./assets/css/2650246020b7.css" scoped/>
<style src="./assets/css/39e022622b71.css" scoped/>
<style src="./assets/css/3d6fbe702d5f.css" scoped/>
<style src="./assets/css/4ec424ddd712.css" scoped/>
<style src="./assets/css/5387e24db001.css" scoped/>
<style src="./assets/css/7420ac8ee48e.css" scoped/>
<style src="./assets/css/90acb788a60a.css" scoped/>
<style src="./assets/css/98d5c242d112.css" scoped/>
<style src="./assets/css/a60ca05a48ba.css" scoped/>
<style src="./assets/css/a64ceb3c719b.css" scoped/>
<style src="./assets/css/c860040ec80a.css" scoped/>
<style src="./assets/css/ccb5e1d1fee8.css" scoped/>
<style src="./assets/css/d3e89dc6a2b0.css" scoped/>
<style src="./assets/css/guide-page.css" scoped/>

<style scoped>
/* HTML中的内联样式 - 完全保留原有样式 */
body, html {
  margin: 0;
  padding: 0;
  background-color: #f0f2f5 !important;
}

.nav {
  position: fixed;
  width: 100%;
  background-color: white;
  height: 60px;
  display: flex;
  align-items: center;
  padding: 0 24px;
  justify-content: space-between;
  /*border-bottom: 1px solid #efefef;*/
  box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);
}

.login-info {
  display: flex;
  align-items: center;
}

.login-info .login-btn {
  color: #fff;
  font-weight: normal;
  background-color: #4caf50;
  width: 72px;
  border: 0 none;
  height: 28px;
  cursor: pointer;
  border-radius: 4px;
  outline: none;
  display: flex;
  justify-content: center;
  align-items: center;
}

.backstage {
  border: 1px solid #4caf50 !important;
  color: #4caf50 !important;
  background-color: white !important;
}

.backstage:hover {
  border: 0 none !important;
  color: white !important;
  background-color: #4caf50 !important;
}

.login-info .login-btn:hover {
  background-color: #43a047;
}

.login-info .item {
  margin-left: 20px;
  font-size: 12px;
  color: rgba(0, 0, 0, .87);
}

.login-info .link {
  color: rgba(0, 0, 0, .87);
  text-decoration: none !important;
}

.login-info a:hover {
  color: #4caf50;
}

.nav-dropdown {
  box-shadow: 0px 0px 4px 0px rgba(0, 0, 0, 0.05);
  position: absolute;
  white-space: nowrap;
  cursor: pointer;
  padding: 8px 12px;
  width: 120px;
  margin-left: -40px;
  top: 30px;
  background-color: white;
  display: none;
}

.drop-down-hover {
  padding-bottom: 30px;
  margin-top: 30px;
}

.drop-down-hover:hover .nav-dropdown {
  display: block;
}

.nav-dropdown:hover {
  background-color: #fafafa;
}

.none {
  display: none;
}

#app {
  position: fixed;
  top: 0;  /* 从顶部开始，盖住header */
  left: 0;
  right: 0;
  bottom: 0;
  overflow-x: scroll;
  z-index: 1;  /* 确保在header之上，但低于菜单按钮 */
}

.x-tooltip {
  display: none;
}

/* 新增的最小样式改动 */

/* 主容器布局 - 保持原有的固定布局 */
.main-container {
  display: flex;
  height: 100%;
}

/* 左侧表单容器 - 独立滚动 */
.form-container {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
  background: white;
}

/* 表单内的标题样式 */
.form-header {
  margin-bottom: 20px;
  padding-bottom: 16px;
  border-bottom: 1px solid #e8e8e8;
}

.form-title {
  margin: 0 0 8px 0;
  font-size: 20px;
  color: rgba(0, 0, 0, 0.85);
}

.form-subtitle {
  font-size: 14px;
  color: rgba(0, 0, 0, 0.45);
}

/* 右侧响应容器 - 独立滚动 */
.response-container {
  width: 700px;
  border-left: 1px solid #ccc;
  padding: 20px;
  overflow-y: auto;
  background: white;
}


/* 表单样式 */
.form-group {
  margin-bottom: 12px;
}

.form-label {
  display: inline-block;
  width: 140px;
  text-align: right;
  margin-right: 8px;
  font-size: 14px;
}

.form-input,
.form-select,
.form-textarea {
  width: 300px;
  padding: 4px 8px;
  border: 1px solid #d9d9d9;
  border-radius: 2px;
  font-size: 14px;
}

.form-input:focus,
.form-select:focus,
.form-textarea:focus {
  border-color: #4caf50;
  outline: none;
}

.form-input[readonly] {
  background-color: #f5f5f5;
}

.form-control-group {
  display: inline-flex;
  gap: 8px;
}

.form-control-group .form-input {
  width: 220px;
}

.form-hint {
  display: block;
  margin-left: 148px;
  margin-top: 4px;
  font-size: 12px;
  color: #999;
}

/* 按钮样式 */
.btn {
  padding: 6px 16px;
  border: 1px solid #d9d9d9;
  border-radius: 2px;
  background: white;
  cursor: pointer;
  font-size: 14px;
}

.btn-primary {
  background-color: #4caf50;
  border-color: #4caf50;
  color: white;
}

.btn-primary:hover {
  background-color: #43a047;
}

.btn-secondary {
  background-color: white;
  border-color: #d9d9d9;
  color: #333;
}

.btn-secondary:hover {
  border-color: #4caf50;
  color: #4caf50;
}

.btn-default {
  background-color: white;
  border-color: #d9d9d9;
  color: #333;
}

.btn-default:hover {
  border-color: #999;
}

.form-actions {
  margin-top: 20px;
  text-align: center;
}

.form-actions .btn {
  margin: 0 8px;
}

/* 响应区域样式 */
.response-title {
  margin: 0 0 16px 0;
  font-size: 18px;
  color: #333;
}

.response-item {
  margin-bottom: 10px;
}

.success-title {
  color: #4caf50;
}

.error-title {
  color: #f44336;
}

.warning-tip {
  background-color: #fff8e1;
  padding: 8px;
  margin-top: 10px;
  border-radius: 2px;
}

.warning-tip p {
  margin: 0;
  color: #ff9800;
}

.code-block {
  background: #f5f5f5;
  padding: 10px;
  overflow: auto;
  font-size: 12px;
  font-family: monospace;
  max-height: 300px;
}

.raw-data {
  margin-top: 20px;
}

.section-title {
  font-size: 14px;
  font-weight: bold;
  margin-bottom: 8px;
}

/* 调整主容器高度，因为footer被隐藏了 */
#app {
  bottom: 0 !important;
}

/* 操作按钮区域 */
.response-actions {
  margin-top: 20px;
  padding-top: 16px;
  border-top: 1px solid #e8e8e8;
}

.response-actions .btn {
  margin-right: 12px;
}

/* 合同状态区域 */
.contract-status {
  margin-top: 20px;
  padding: 16px;
  background: #f7f7f7;
  border-radius: 4px;
}

.contract-status h5 {
  margin: 0 0 12px 0;
  font-size: 16px;
  color: #333;
}

.status-item {
  margin-bottom: 8px;
  font-size: 14px;
}

/* 状态标签样式 */
.status-pending {
  color: #666;
}

.status-submitted {
  color: #1890ff;
}

.status-signing {
  color: #fa8c16;
}

.status-completed {
  color: #52c41a;
  font-weight: bold;
}

.status-failed {
  color: #f5222d;
}

.status-rejected {
  color: #cf1322;
}

.status-unknown {
  color: #999;
}

/* 签约链接区域 */
.result-url {
  margin-top: 8px;
}

.sign-link {
  display: inline-block;
  margin: 8px 0;
  color: #4caf50;
  text-decoration: none;
  font-weight: bold;
}

.sign-link:hover {
  text-decoration: underline;
}

.url-textarea {
  width: 100%;
  padding: 8px;
  margin-top: 8px;
  border: 1px solid #d9d9d9;
  border-radius: 2px;
  font-size: 12px;
  resize: none;
}
</style>

<!-- 全局样式用于隐藏footer -->
<style>
/* 隐藏页面footer */
.footer {
  display: none !important;
}

/* 确保菜单按钮（三横线）在最上层 */
.ant-layout-header .anticon-menu,
.header-menu-trigger,
[class*="menu-trigger"],
[class*="menu-icon"] {
  position: relative;
  z-index: 10 !important;
}

/* 如果菜单按钮在header右侧 */
.ant-layout-header > *:last-child {
  position: relative;
  z-index: 10;
}
</style>
